import os
import tempfile
from typing import Callable
from fastapi import FastAPI
from .database import db_manager
from .init_data.data_initialize import init_admin_user, init_setting
from .config import reload_config


def startup(app: FastAPI) -> Callable:
    async def app_start():
        init_app_config()
        await db_manager.initialize()
        await init_admin_user()
        await init_setting()
        exists_data = await db_manager.fetch_all("SELECT name,value FROM setting")
        setting_data = {}
        for item in exists_data:
            setting_data[item["name"]] = item["value"]
        reload_config(setting_data)
        print(u"启动完成")
    return app_start


def stopping(app: FastAPI) -> Callable:
    async def stop_app():
        await db_manager.close()
        print(u"应用停止")
        # await Tortoise.close_connections()

    return stop_app


def init_app_config() -> None:
    """初始化应用配置"""
    os.makedirs(f"{tempfile.gettempdir()}/pkgm", exist_ok=True)
